import styles from './index.module.less';
import { Drawer, Menu as AntMenu, Button } from 'antd';
import { MenuUnfoldOutlined } from '@ant-design/icons';
import { NavLink } from 'react-router';
import type { MenuProps } from 'antd';
import type { RouteObject } from 'react-router';
import { useState, useMemo } from 'react';
import { useLocation } from 'react-router';
import { routes } from '@/router';
import { findPathOfValue } from '@hdtd/utils';

interface IGetMenuItemsFcState {
  parentKey: string;
}

const getMenuItems = (
  routes: Array<RouteObject>,
  menuItems: MenuProps['items'] = [],
  state: IGetMenuItemsFcState = { parentKey: '' }
) => {
  routes.forEach((item) => {
    if (item.index) return;
    let menuItem: Exclude<MenuProps['items'], undefined>[number] = {
      key: `${state.parentKey}/${item.path}`
    };
    if (item.element) {
      menuItem.label = <NavLink to={`/admin${state.parentKey}/${item.path}`}>{item.path}</NavLink>;
    } else if (item.children?.length) {
      menuItem = {
        key: menuItem.key,
        label: item.path!,
        children: []
      };
      getMenuItems(
        item.children,
        (menuItem as Extract<Exclude<MenuProps['items'], undefined>[number], { children: any }>)
          .children,
        { parentKey: menuItem!.key! as string }
      );
    }
    menuItems.push(menuItem);
  });
  return menuItems;
};

const Menu = () => {
  const location = useLocation();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const menuRoutes = useMemo(
    () =>
      (routes.find((item) => item.path === '/admin')?.children ?? []).filter(
        (item) => item.path !== '*'
      ),
    []
  );
  const menuItems = useMemo(() => getMenuItems(menuRoutes), []);

  const activePath = useMemo(
    () =>
      findPathOfValue<any>(menuItems, { targetKey: 'key', matchValue: location.pathname.slice(6) }),
    [location.pathname, menuItems]
  );
  const selectedKeys = useMemo(() => activePath?.map((item) => item.key), [activePath]);
  return (
    <>
      <Drawer open={drawerOpen} placement="left" title="菜单" onClose={() => setDrawerOpen(false)}>
        <AntMenu
          items={menuItems}
          selectedKeys={selectedKeys}
          defaultOpenKeys={selectedKeys}
          mode="inline"
        />
      </Drawer>
      {!drawerOpen && (
        <Button className={styles['show-menu-btn']} onClick={() => setDrawerOpen(true)}>
          <MenuUnfoldOutlined />
        </Button>
      )}
    </>
  );
};

export default Menu;
